import { Hono } from 'hono';
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
import { AuthController } from '../../controllers/AuthController';
import { DataSource } from 'typeorm';

// 验证模式
const registerSchema = z.object({
  email: z.string().email(),
  name: z.string().min(1).max(255),
  password: z.string().min(6).max(100),
});

const loginSchema = z.object({
  email: z.string().email(),
  password: z.string().min(1),
});

const refreshTokenSchema = z.object({
  refreshToken: z.string(),
});

export function createTestAuthRoutes(dataSource: DataSource) {
  const authRoutes = new Hono();
  const authController = new AuthController(dataSource);

  // 用户注册
  authRoutes.post(
    '/register',
    zValidator('json', registerSchema),
    async (c) => {
      try {
        const data = c.req.valid('json');
        const result = await authController.register(data);
        
        return c.json({
          success: true,
          data: result,
        });
      } catch (error) {
        return c.json({
          success: false,
          error: error instanceof Error ? error.message : 'Registration failed',
        }, 400);
      }
    }
  );

  // 用户登录
  authRoutes.post(
    '/login',
    zValidator('json', loginSchema),
    async (c) => {
      try {
        const data = c.req.valid('json');
        const ip = c.req.header('x-forwarded-for') || c.req.header('x-real-ip') || 'unknown';
        const result = await authController.login(data, ip);
        
        return c.json({
          success: true,
          data: result,
        });
      } catch (error) {
        return c.json({
          success: false,
          error: error instanceof Error ? error.message : 'Login failed',
        }, 401);
      }
    }
  );

  // 刷新令牌
  authRoutes.post(
    '/refresh',
    zValidator('json', refreshTokenSchema),
    async (c) => {
      try {
        const { refreshToken } = c.req.valid('json');
        const result = await authController.refreshToken(refreshToken);
        
        return c.json({
          success: true,
          data: result,
        });
      } catch (error) {
        return c.json({
          success: false,
          error: error instanceof Error ? error.message : 'Token refresh failed',
        }, 401);
      }
    }
  );

  // 验证令牌
  authRoutes.get('/verify', async (c) => {
    try {
      const authHeader = c.req.header('Authorization');
      if (!authHeader || !authHeader.startsWith('Bearer ')) {
        return c.json({
          success: false,
          error: 'Authorization header missing or invalid',
        }, 401);
      }

      const token = authHeader.substring(7);
      const user = await authController.verifyToken(token);
      
      if (!user) {
        return c.json({
          success: false,
          error: 'Invalid or expired token',
        }, 401);
      }

      return c.json({
        success: true,
        data: { user: user.toSafeJSON() },
      });
    } catch (error) {
      return c.json({
        success: false,
        error: error instanceof Error ? error.message : 'Token verification failed',
      }, 401);
    }
  });

  // 用户登出
  authRoutes.post('/logout', async (c) => {
    try {
      const authHeader = c.req.header('Authorization');
      if (!authHeader || !authHeader.startsWith('Bearer ')) {
        return c.json({
          success: false,
          error: 'Authorization header missing or invalid',
        }, 401);
      }

      const token = authHeader.substring(7);
      await authController.logout(token);
      
      return c.json({
        success: true,
        data: { message: 'Logged out successfully' },
      });
    } catch (error) {
      return c.json({
        success: false,
        error: error instanceof Error ? error.message : 'Logout failed',
      }, 400);
    }
  });

  return authRoutes;
}
